package com.itgone.easyblog.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itgone.easyblog.config.BlogServiceException;
import com.itgone.easyblog.mapper.BlogMapper;
import com.itgone.easyblog.entity.Blog;
import com.itgone.easyblog.model.UpdateBlogReqModel;
import com.itgone.easyblog.service.image.impl.QnyFileService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Objects;

/**
 * (TBlog)表服务接口
 *
 * @author Earlman
 * @since 2023-03-24 13:54:19
 */
@Service
public class BlogService extends ServiceImpl<BlogMapper, Blog> {

    @Resource
    private QnyFileService qnyFileService;

    @Override
    public Blog getById(Serializable id) {
        Blog byId = super.getById(id);
        if (Objects.isNull(byId)) {
            throw new BlogServiceException("博客信息不存在");
        }
        return byId;
    }

    public Object updateBlog(UpdateBlogReqModel blogModel, MultipartFile titlePicFile) {
        String blogId = blogModel.getId();
        Blog byId = getById(blogId);
        BeanUtils.copyProperties(blogModel, byId);

        if (Objects.nonNull(titlePicFile)) {
            String upload = qnyFileService.upload(titlePicFile);
            byId.setTitlePic(upload);
        } else {
            byId.setTitlePic(null);
        }

        updateById(byId);
        return byId;
    }
}

